package com.huawei.cloud.phone.management.infrastructure.db.mapper;

import com.huawei.cloud.phone.management.infrastructure.db.datasource.DataSourceName;
import com.huawei.cloud.phone.management.infrastructure.db.datasource.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class MapperAop {

    @Pointcut(value = "execution(* com.huawei.cloud.phone.management.infrastructure.db.mapper.*.*(..))")
    public void mapperPoint() {
    }

    @Around("mapperPoint()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String name = methodSignature.getMethod().getName();
        if (name.startsWith("get")) {
            DynamicDataSource.setDatasourceName(DataSourceName.MASTER);
        } else {
            DynamicDataSource.setDatasourceName(DataSourceName.MASTER);
        }

        try {
            return joinPoint.proceed();
        } finally {
            DynamicDataSource.clearDataSourceName();
        }
    }

}
